<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>TMS Service</title>
    <script>
        var CONFIG ={
            updateRouterUrl:"{{:url('/tms/UpdateRouter')}}",
            updateRouterDriver:"{{:url('/tms/UpdateRouterDriver')}}",
            getRouterUrl:"{{:url('/tms/GetRouters')}}",
            allRoutersUrl:"{{:url('/tms/router')}}",
            checkTerritoryIsExist:"{{:url('/territory/isExist')}}",
            saveTerritory:"{{:url('/territory/create')}}",
            territoryList:"{{:url('/territory/lists')}}",
            deleteTerritory:"{{:url('/territory/delete')}}",
            moveRouters:"{{:url('/router/move')}}",
            routerStrokeColor:['#00AFE4','#f20','#388bff','#1f1e1e','#000','#0c08ab','#1d3e1d','#003f59','#3ca009','#298fca','#FF9900','#FF9933','#993333','#003366','#003366','#00AFE4','#f20','#388bff','#1f1e1e','#000','#0c08ab','#1d3e1d'],
            doRecord:[],                         //操作记录
            currentOpearateRouterId:null,         //当前操作的路由id
            showOrHideSatues:"show",                //隐藏or显示状态 （show,hide）
            zoom:10,
            latAndLngPrecision:4,                    //经纬度精确到几位小数
            checkUnAssignTimeInterval:1000,          //定时检查有没有未分配的站点时间间隔
            updateRouterPointsTimeInterval:1000,     //定时更新Router详情模板内容的站点时间间隔
            delayPointsCounter:0,                   //到达客户地址超时记录数
            keydownAddRouterBtn:false,               //是否按下添加路由按钮
            drawingRouterEdgePoints:[]  ,     //添加多边形的四个顶点
            assignRouterTimer:null,           //分配站点到区域定时器
            updateRouterTimer:null,           //更新路线数据到服务器定时器
            driverPositionShowStatus:"false",
            addRouterNameTempValue:null,            //添加Router临时存放Route名字
            optimizeOrderpoints:[]    ,                 //路线站点顺序是否优化配置,手动初始化为ture，从历史记录恢复为false 如果值为true的话 则对路线站点按照收货时间排序
            wareHouseCenter:null,
            wareHouseCode:"{{$Think.get.wareHouse}}",
            territoryName:null ,                       //当前territory名字
            showRouters:false                         //是否显示Routers   当值为true的时候，不再画多边形
        }
        var OBJECT = {
            directionsDisplay:[],   //路线图对象容器
            bermudaTriangle  : [],   //背景区域对象容器
            markers:[],               //标记聚类对象容器
            markerCluster:[] ,      //标记聚类对象句柄容器
            routersBgColorMap:[] ,  //路线对应的颜色 [routerId=>color]
            routersNameMap:[] ,  //路线对应的颜色 [routerId=>NAME]
            filterMarker:[],        //筛选出来的标记对象容器
            routerPonits:[],          //每条路线的地点 {points:每个地点,vehicleId：vehicleId，driver:driver,schedule:每条路线之间的点距离和时间,UpdateStatus:true or false}
            driverList :[],          //司机列表
            driverMarketList :[],          //司机标记对象容器
            CustomerList :[],          //客户标记对象容器 存放所有的客户信息
            vehicleList:[] ,               //车辆列表
            routerEdgePoints:[] ,          //每个router多边形的顶点
            customerPositionList:[],       //每个客户的信息
            dispalyPositonList:[],        //每个多边形的标记容器
            numberMarkerOnRouter:[],       //Router上每个数字Market (ABCD....=>1234....)
            exceptionRouter:new Set(),      //每个Router异常信息 （配送超时，超过上班最大时间,超出磅数）
            driverWaitOverOneHour:new Set(),     //司机等待超过一个小时
            requestRoutePromiseHandle:[] ,               //Promise 对象容器
          //  requestRouteStatus:new Map()  ,             //请求Route状态    [routerId=>status( success or pending)]
            infowindow:[],                             //Marker
            beforeMoveToOthersRouters:[],             //保存未移动到另一个Territory的Routers  第一个为当前的territoy 第二个为被移动的目标

        };


    </script>
    <script  src="__STATIC__/static/js/jquery.js"></script>
    <script  src="__STATIC__/static/js/common.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.10.0/js/md5.min.js"></script>
    <link rel="stylesheet" href="__STATIC__/static/css/router.css?v={{:config('STATIC_VERSION')}}">
    <link rel="stylesheet" href="__STATIC__/static/css/move-router.css?v={{:config('STATIC_VERSION')}}">
    <link rel="stylesheet" href="__STATIC__/static/css/jq-tab.css?v={{:config('STATIC_VERSION')}}">
    <link rel="stylesheet" href="__STATIC__/static/css/tableStyle.css?v={{:config('STATIC_VERSION')}}">
    <link rel="stylesheet" href="__STATIC__/static/css/loading.css?v={{:config('STATIC_VERSION')}}">
    <link href="__STATIC__layui/css/layui.css" rel="stylesheet">
    <script  src="__STATIC__/static/js/Polygon.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/RecordAndRestore.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Router.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Marker.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/jq-tab.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/handlebars-v4.0.11.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Territory.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/getEdgePoints.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/assignRoute.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Server.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Driver.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/assignDriver.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/Customer.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/alert.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/resizeTerritoryTable.js?v={{:config('STATIC_VERSION')}}"></script>
    <script  src="__STATIC__/static/js/RecoveryFromRouteHistory.js?v={{:config('STATIC_VERSION')}}"></script>
    <script type="text/javascript" src="__STATIC__/layui/layui.all.js"></script>



    <!--函数区域-->

    <script>

        var map;
        var drawingManager;
        var RecordAndRestoreObj = new RecordAndRestore();
        var MarkerObj = new Marker();
        function objToArray(data) {
            let ret = [];
            for(var i=0;i<data.length;i++){
                let o={};
                for(let key in data[i]){
                    o[key] = data[i][key]
                }
                ret.push(o)
            }
            for(let i=0;i<ret.length;i++ ) {
                ret[i].lat = Number(ret[i].lat);
                ret[i].lng = Number(ret[i].lng);
            }
            return ret;
        }
        function getRoutetsAndShow() {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "{{:url('/tms/router')}}" ,
                data: {},
                success: function (result) {
                    $.each(result.body,function (key,value) {
                        routers = objToArray( value.routers );

                            //Polygon.draw(routers,map ,value.id,key);
                          //  Router.getInstance().calculateAndDisplayRoute(routers,value.id,key);
                    })
                },
                error : function() {}
            });
        }
        /**
         * 获取车数据列表
         */
        function getVehicleList(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/vehicle/index")}}' ,
                data: {},
                success: function (result) {
                    OBJECT.vehicleList = result.msg.data;

                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取今天Route列表
         */
        function getRouters(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/tms/router")}}' ,
                data: {warehouse:CONFIG.wareHouseCode},
                success: function (result) {
                    RecoveryFromRouteHistory.getInstance().render( result.body );
                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取车数据列表
         */
        function getWareHouse(resolve){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/warehouse/get")}}' ,
                data: {warehouse:CONFIG.wareHouseCode},
                success: function (result) {
                    CONFIG.wareHouseCenter = result.msg;
                    resolve('SUCCESS');
                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取司机列表
         */
        function getDriverList( resolve= null){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/driver/warehouse/itmes")}}' ,
                data: {warehouse:CONFIG.wareHouseCode},
                success: function (result) {
                    OBJECT.driverList = result.msg.data;
                    resolve && resolve('SUCESS');
                },
                error : function() {
                    alert('获取信息失败')
                }
            });
        }
        /**
         * 获取订单列表
         */
        function getOrderList(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: '{{:url("/order/all")}}' ,
                data: {wareHouse:CONFIG.wareHouseCode},
                success: function (result) {

                    OBJECT.customerPositionList = objToArray(result.msg);
                    Customer.getInstance().render(OBJECT.customerPositionList);
                  //  Server.getInstance().assignPointToPolygon();
                },
                error : function() {
                    alert('获取信息失败');
                }
            });
        }

        function initMap() {
            showLoading();
            new Promise(function (resolve, reject) {
                getWareHouse(resolve);
            }).then(function(value){
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: CONFIG.zoom,
                    center: {lat: Number(CONFIG.wareHouseCenter.lat), lng:Number(CONFIG.wareHouseCenter.lng)},
                    mapTypeId: 'roadmap'
                });
                google.maps.event.addDomListener(map, 'zoom_changed', function() {
                    CONFIG.zoom = map.getZoom();
                });
                drawingManager = new google.maps.drawing.DrawingManager({
                    drawingControl: true,
                    drawingControlOptions: {
                        position: google.maps.ControlPosition.TOP_CENTER,
                        drawingModes: ['polyline']
                    },
                });
                google.maps.event.addListener(drawingManager, 'polylinecomplete', function (e) {
                    //获取所有顶点
                    let paths = e.getPath().getArray();
                    paths.forEach( function ( value ,index ) {
                        let lat = (value.lat()).toFixed(5);
                        let lng = (value.lng()).toFixed(5);
                        CONFIG.drawingRouterEdgePoints.push({lat:Number(lat),lng:Number(lng)})
                    })
                    let routerId = getRandomRouterId();
                    initApp(routerId, CONFIG.drawingRouterEdgePoints )
                    Queue(routerId)
                    CONFIG.keydownAddRouterBtn = false;
                    e.setMap(null);   //清空多边形
                    drawingManager.setMap(null)

                });

               getOrderList();

                new Promise(function(resolve, reject) {
                    getDriverList();
                    getVehicleList();

                    setTimeout(()=>{
                        resolve('SUCCESS');
                    },2000)
                }).then(function (status) {
                    getRouters();
                   // Server.getInstance().requestRouter();
                    closeLayerMsg();
                })
            });
            colseLoading();
        }
    </script>
</head>
<body>



<!--loading 按钮-->
<div class="mask"></div>
<div class="loader">
    <div class="square" ></div>
    <div class="square"></div>
    <div class="square last"></div>
    <div class="square clear"></div>
    <div class="square"></div>
    <div class="square last"></div>
    <div class="square clear"></div>
    <div class="square "></div>
    <div class="square last"></div>
</div>
<!--loading 按钮-->
<div class="header">
    <div class="logo"></div>
    <div class="info">

        <span style="display: none;">3562.23</span>
        <span>{{$Think.session.username}}</span>
    </div>
</div>
<div class="nav-title">
    <div class="tab-text">
        Route
    </div>

    <div class="info">
        <?php echo date('Y-m-d');?> Maywood
    </div>
    <script></script>
    <div class="right">
        <span onclick="RecordAndRestoreObj.restore()" style="display: none;">撤回</span>
    </div>
</div>
<div class="work-area">
    <div class="open-show-btn open"></div>
    <div class="menus ">
        <ul>
            <li class="active"><span>Customers</span></li>
            <li onclick="showDriverList()"><span>Drivers</span></li>
            <li onclick="renderVehicleList()"><span>Vehicles</span></li>
            <li><span>Depost</span></li>
            <li onclick="assignRoute.getInstance().render()"><span>Routes</span></li>
            <li><span>Notes</span></li>
        </ul>
        <div class="clear"></div>
        <div class="tab  show">
            Customers
        </div>
        <div class="tab ">
            <div id="driver-list" class="driver-list overflow-auto" >

            </div>
        </div>
        <div class="tab ">
           <div  id="vehicle-list" class="vehicle-list overflow-auto">

           </div>
        </div>
        <div class="tab">
            Depost
        </div>
        <div class="tab" id="route-list-tab-btn" >
            <div id="route-list" class="route-list overflow-auto" style="height: 400px !important;"></div>
            <div id="route-points-list" class="route-points-list overflow-auto" style="min-height: 400px !important;max-height: 700px;"></div>
        </div>
        <div class="tab ">
            Notes
        </div>
    </div>

</div>
<div id="map" class="map"></div>
<div  class="side-bar-menu" style="display: none">

</div>

<div  class="side-bar-market-menu layui-form">
    <div class="title">Marker</div>
    <div class="btn">
        <span onclick="">Driver</span>
        <div class="layui-form-item my-layui-form-item" >
            <input type="checkbox"  name="close" lay-skin="switch" lay-filter="showDriver" lay-text="ON|OFF">
        </div>
    </div>
    <div class="btn">
        <span id="show-schedule-time" data-status="Hide">Schedule</span>
        <div class="layui-form-item my-layui-form-item" >
            <input type="checkbox"  name="close" lay-skin="switch" lay-filter="showScheduleTime" lay-text="ON|OFF">
        </div>
    </div>

</div>
<div  class="side-bar-menu-btns">
    <p>Menus</p>
    <span onclick="Router.getInstance().add()" class="new-territory" title="New Territory"></span>
    <span id="show-routes" data-status="Hide" class="show-routers" title="Show Routers"></span>
    <span id="update-driver" data-status="Hide" class="update-driver" title="Update Driver"></span>
    <span id="router-history" data-status="Hide" class="router-history" title="Router History"></span>
    <span id="territory-manage" data-status="Hide" class="territory-history" title="Territoy List"></span>
    <span href="javascript:;" class="save save-territory" title="Save"  id="save-territory" ></span>
    <span href="javascript:;" class="undo-move-router" title="Undo Move Router"  id="undo-move-router" onclick="Router.getInstance().renewBeforeMoveRouters()" ></span>
</div>
<!--<div  class="side-bar-market-menu layui-form">
    <span onclick="Driver.getInstance().render()">Driver</span>
    <div class="layui-form-item" >
        <input type="checkbox"  name="close" lay-skin="switch" lay-filter="showDriver" lay-text="ON|OFF">

    </div>
    <span onclick="Router.getInstance().add()">Add Router</span>
    <span id="show-routes" data-status="Hide">Routers</span>
    <div class="layui-form-item" >
        <input type="checkbox"  name="close" lay-skin="switch" lay-filter="showRouter" lay-text="ON|OFF">

    </div>
    <span id="update-driver" data-status="Hide">Update Driver</span>
    <span id="router-history" data-status="Hide">Router History</span>

    <span id="show-schedule-time" data-status="Hide">Show Schedule</span>
    <span id="territory-manage" data-status="Hide">Territory Manage</span>
    <span href="javascript:;" class="save" title="Save" id="save-territory" class="save-territory">Save Territory</span>
</div>-->
<div  class="un-assign-warning">
     UnAssign Points <span class="">0</span>
</div>
<div  class="delay-warning">
    Delay Points <span class="">0</span>
</div>

<script   src="https://maps.googleapis.com/maps/api/js?key={{:config('GOOGLE_MAP_API_KEY')}}&callback=initMap&libraries=geometry,drawing"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script src="__STATIC__/static/js/table-drap-sort.js?v={{:config('STATIC_VERSION')}}"></script>
<script>
    Handlebars.registerHelper("drawRouterIcon",function(value){
            return `<span style="background: ${value};width: 18px;height: 18px;display: block;"></span>`;
    });
    Handlebars.registerHelper("getIndex",function(value){
        return  value + 1;
    });
    Handlebars.registerHelper("getDelayStyle",function(value){
        if(value.delay){
            return `color:red`;
        }
    });
    Handlebars.registerHelper("isExcetion",function(value){
        if(OBJECT.exceptionRouter.has( value ))
        {
            return `color:red;`
        }
        return '';
    });

    Handlebars.registerHelper("formateJsonToString",function(data){
          return JSON.stringify(data)
    });
    Handlebars.registerHelper("getSelectMonth",function(index){
         if(index==0){
             return 'selected';
         }
    });

    Handlebars.registerHelper("getDriverDepartureInfo",function( data ){
        let routerId = CONFIG.currentOpearateRouterId;
        let driverId = OBJECT.routerPonits[routerId].driverId;
        let driver = null;
        OBJECT.driverList.forEach( function ( value ,index ) {
               if( value.driver_id == driverId )
               {
                   driver = value;
               }
        });
        return `  <tr >
                      <th colspan="9" style="font-weight: bold;">
                      &nbsp;&nbsp;&nbsp;&nbsp;Lacation :${CONFIG.wareHouseCenter.address}
                      <br/>
                      &nbsp;&nbsp;&nbsp;&nbsp;WorkHour:${driver.work_hours}h &nbsp;&nbsp;&nbsp;&nbsp; End Location:${driver.end_location}&nbsp;&nbsp;&nbsp;&nbsp;DepartrueTime :${driver.departure_time}
                      </th>
                 </tr>`
    });



</script>
<!--territory-manage template-->

<!--路由列表模板-->

<script type="text/template" id="route-list-template">

    <table class="bootsrtop-table" id="route-list-table" style="width: 700px;">
        <thead>
        <tr>
            <th></th>
            <th></th>
            <th>Name</th>
            <th>Drivers</th>
            <th>Vehicles</th>
            <th>Stops</th>
            <th>Distance</th>
            <th>Hours</th>
            <th>lbs(Total)</th>
        </tr>
        </thead>
        <tbody>
        {{#each data}}
       <!-- <tr  class="showRoutePoints" data-router="{{routerId}}" data-driver="{{driver}}" style="{{isExcetion routerId}}">-->
        <tr  class="showRoutePoints" data-router="{{routerId}}" data-driver="{{driver}}" >
            <th>
                <a href="javascript:;" style="text-decoration: none;font-size: 26px;" class="deleteRouter" title="Delete" data-router="{{routerId}}">-</a>
            </th>
            <th >{{{drawRouterIcon routerBg}}}</th>
            <th >{{{name}}}</th>
            <td>{{driver}}</td>
            <td>{{vehicleId}}</td>
            <td>{{stops}}</td>
            <td>{{distance}}(英里)</td>
            <td>{{time}}(h)</td>
            <td>{{lbs}}</td>
        </tr>
        {{/each}}
        </tbody>
    </table>

</script>
<script type="text/template" id="set-route-list-template">

    <table class="bootsrtop-table" >
        <thead>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Drivers</th>
            <th>Vehicles</th>
            <th>Stops</th>
            <th>Distance</th>
            <th>Hours</th>
            <th>lbs(Total)</th>
            <td>Opreate</td>
        </tr>
        </thead>
        <tbody>
        {{#each data}}
        <tr>
            <th >{{{drawRouterIcon routerBg}}}</th>
            <th >{{{name}}}</th>
            <td>{{driver}}</td>
            <td>{{vehicleId}}</td>
            <td>{{stops}}</td>
            <td>{{distance}}(英里)</td>
            <td>{{time}}(h)</td>
            <td>{{lbs}}</td>
            <td >
                <a
                   href="javascript:;"
                   onclick="addRouterForDriver('{{../driver_id}}','{{routerId}}','{{driver}}')"
                   data-assignStatus="{{driver}}"
                   title="Add Router"
                   style="text-decoration: none;font-size: 12px;"
                >+</a>&nbsp;
                &nbsp;
                <a
                    href="javascript:;"
                    onclick="unAssignRouterForDriver('{{routerId}}')"
                    data-assignStatus="{{driver}}"
                    title="Unassing Router"
                    style="text-decoration: none;font-size: 12px;"
            >-</a></td>
        </tr>
        {{/each}}
        </tbody>
    </table>

</script>
<script type="text/template" id="route-points-list-template">
    <h2>{{driver}}</h2>
    <table class="bootsrtop-table " id="table-sort" style="width: 700px;" >
        <thead class="nobg">
        <tr>
        <th>NO</th>
        <th width="100px">Schedule</th>
        <th>ScheduleTime</th>
        <th>Minute</th>
        <th>Arrive Time</th>
        <th>lbs</th>
        <th>Distance</th>
        <th>Location</th>
        <th>Address</th>

    </tr>
    </thead>
    <tbody id="route-points-list-body">
    {{{getDriverDepartureInfo @this}}}

    {{#each data}}
    {{#if exception}}
    <!--司机去吃午饭-->
         <tr><td colspan="9" style="color: red" >Lunch Time {{duration}} 分钟 </td></tr>
    {{/if}}
    <!--司机正常配送-->
    {{#if arriveTime}}
    <tr data-key="{{@index}}" id="row_{{getIndex @index}}" class="route-points-info" style="{{getDelayStyle this}}">
        <td>{{getIndex @index}}</td>
        <td>{{ScheduleID}}</td>
        <td>{{ScheduleTime}}</td>
        <td>{{minute}}</td>
        <td>{{arriveTime}}</td>
        <td>{{lbs}}</td>
        <td>{{distance}}</td>
        <td>{{CustomerTag}}</td>
        <td>{{Address}}</td>
    </tr>
    {{/if}}
    {{/each}}

    </tbody>
    </table>
</script>

<script type="text/template" id="date-pickr">
        <div class="date-pickr">
            <div class="ago-month">
                {{#each month}}
                <span class="{{getSelectMonth @index}} ago-month-items" data-month="{{month}}" data-year="{{year}}" >{{text}}</span>
                {{/each}}
            </div>
            <div class="ago-month-days">
                {{#each day}}
                <span class="ago-days" data-day="{{text}}">{{text}}</span>
                {{/each}}
            </div>
        </div>

</script>
<!--territory-list-->
<script type="text/template" id="territory-list-template">
    <ul class="territory-list">
        {{#each data}}
        <li data-points='{{formateJsonToString points}}' data-title="{{title}}">{{day}}&nbsp;&nbsp;{{warehouse}}&nbsp;&nbsp;{{title}}</li>
        {{/each}}
    </ul>
</script>
<script type="text/template" id="driver-list-template">
    <select name="driver-filter" id="driver-filter" class="driver-filter" onchange="showDriverList(this.value)">
        <option value="all" >All</option>
        <option value="unAssign">unAssign</option>
    </select>
    <table class="bootsrtop-table driver-list-table" style="width: 700px !important;">
        <thead class="nobg">
        <tr>
            <th width="90">Driver Id</th>
            <th width="120px">Vehicle Id</th>
            <th width="120px">NickName</th>
            <th width="120px">Start Location</th>
            <th width="120px">End Location</th>
            <th width="250px;">Address</th>
        </tr>
        </thead>
        <tbody id="driver-list-table-body">
        {{#each data}}
        <tr onclick="setRoute('{{driver_id}}')">
            <td>{{driver_id}}</td>
            <td>{{vehicle_id}}</td>
            <td>{{nickname}}</td>
            <td>{{start_location}}</td>
            <td>{{end_location}}</td>
            <td>{{address}}</td>
        </tr>
        {{/each}}
        </tbody>
    </table>
</script>
<script type="text/template" id="vehicle-list-template">
    <table class="bootsrtop-table" >
        <thead class="nobg">
        <tr>
            <th width="90">Vehicle Id</th>
            <th width="90">Name</th>
            <th width="120px">Depot</th>
            <th width="120px">Max Stops</th>
        </tr>
        </thead>
        <tbody>
        {{#each data}}
        <tr>
            <td>{{vehicle_id}}</td>
            <td>{{name}}</td>
            <td>{{depot}}</td>
            <td>{{max_stops}}</td>
        </tr>
        {{/each}}
        </tbody>
    </table>
</script>


<script>

   /*在左侧工作台显示司机数据*/
   function showDriverList (filter = 'all') {
       let source=$('#driver-list-template').html();
       let template = Handlebars.compile(source);
       let data=[];
       if( filter=='all' )
       {
           data = OBJECT.driverList;
           $('#driver-list').html(template({data:data}));
       }else{
           let assignedDriverId = Driver.getInstance().getAssignedDriver();
           //driver-list-table-body"
           let html='';
           OBJECT.driverList.forEach(function ( value ,index ) {
                 if( assignedDriverId.indexOf( value.driver_id) < 0 )
                 {
                     html+=` <tr onclick="setRoute('${value.driver_id}')">
                                <td>${value.driver_id}</td>
                                <td>${value.vehicle_id}</td>
                                <td>${value.nickname}</td>
                                <td>${value.start_location}</td>
                                <td>${value.end_location}</td>
                                <td>${value.address}</td>
                            </tr>`;
                     $('#driver-list-table-body').html(html)
                 }
           })
       }


   }
  /**
   *显示日期列表框
   */
  function showDatePickr (element , title , callback) {
      $(element).click( function () {
          let month = getAgoMonth(3);
          let source=$('#date-pickr').html();
          let day = getDays(month[0].year,month[0].month)
          let template = Handlebars.compile(source);
          let html = template({month:month,day:day});
          $.Pop(html,{Close:true,Title:title,Btn:{yes:{vla:"确定"}}});
          $(document).on('click','.ago-month-items',function () {
              $(this).siblings().removeClass('selected');
              $(this).addClass('selected');
              let month = $(this).data('month');
              let year = $(this).data('year');
              let days = getDays(year,month);
              let daysHtml='';
              for (let i=0;i<days.length;i++)
              {
                  daysHtml+=`<span class="ago-days" data-day="${days[i].text}">${days[i].text}</span>`
              }
              $('.ago-month-days').html( daysHtml);
              //<span class="ago-days" data-day="2018-4-02">2018-4-02</span>

          });
          callback();
      })

  }
  /**
   * 点击日期 生成对应的区域和司机数据
   */
  showDatePickr('#router-history','Router History',function () {
      $(document).on('click','.ago-days',function () {
          let day = $(this).data('day');
          new Promise(function( resolve, reject){
              $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: "{{:url('/router/getDayRouter')}}",
                  data: {day:day,warehouse:"{{$Think.get.wareHouse}}"},
                  success: function (result) {
                      if(result.code==200)
                      {
                          resolve(result.msg);
                      }else{
                          reject(result.msg)
                      }
                  }
              });
          }).then( function (value) {
              //设置Router数据来源
              CONFIG.routerDataFromDate = day;
              Territory.getInstance().createTerritory( value );
          },function (errror) {
              $.Pro(errror);
          })
      })
  });


/*对客户客户有时间要求的显示Market*/
/*$('#show-schedule-time').click(function () {
       let status = $(this).data('status');
       if(status=='Hide')
       {
           Customer.getInstance().showScheduleTime();
           $(this).data('status','Show');
           $(this).text('Hide Schedule')
       }else{
           Customer.getInstance().hideScheduleTime();
           $(this).data('status','Hide');
           $(this).text('Show Schedule')
       }
});*/





   function renderVehicleList () {
       let source=$('#vehicle-list-template').html();
       let template = Handlebars.compile(source);
       let html = template({data:OBJECT.vehicleList});
       $('#vehicle-list').html(html)
      // $.Pop(html,{Close:true,Title:'设置路线',Btn:{yes:{vla:"确定"}}})
   }
   /**
    * 设置路线名称
    **/
   function setRouteName()
   {
       $.Pop(`<input id="routerName" value="No Title" style="width: 220px;height: 30px;padding-left: 10px;margin: 10px auto;display: block" onblur="CONFIG.addRouterNameTempValue=this.value">`,{Close:true,Title:'路线名称',Btn:{yes:{vla:"确定"}}})
   }

   /**
    * 司机设置路线
    *
    */
   function setRoute(driver_id)
   {

       let html = getSetRouterHtml(driver_id);
       $.Pop(html,{Close:true,CloseBtn:true,Title:'设置路线',Btn:{yes:{vla:"确定"}}})
   }
   /***
    * 获取司机设置路线模板
    * */
   function getSetRouterHtml(driver_id)
   {
       let source=$('#set-route-list-template').html();
       let template = Handlebars.compile(source);
       let html = template({data:assignRoute.getInstance().getRouters(),driver_id:driver_id});
       return html;
   }
   /**
    * 增加Router
    **/
  function addRouterForDriver( driverId,routerId , assignStatus)
  {
      if(assignStatus!='UnAssign')
      {
          $.Pro('该路线已经分配');
          return false;
      }
      if(Router.getInstance().DriverIsAssign( driverId ))
      {
          $.Pro('该司机已经被分配路线了');
          return false;
      }

      let driverIsForbid = Customer.getInstance().driverIsForbid( OBJECT.routerPonits[routerId].points , driverId );
      if( driverIsForbid.isForbid === true )
      {
          $.Pro(`${driverIsForbid.driverName}司机已禁止`);
          return false;
      }
      OBJECT.routerPonits[routerId].driverId = driverId;
      OBJECT.routerPonits[routerId].vehicleId = getVehicleIdByDriverId( driverId );
      Server.getInstance().updateRouters(routerId);
      $.Pro('设置成功');
  }

  /**
   * 更新车辆数据
   */
  $('#update-driver').click( function () {
      new Promise(function (resolve,reject) {
          getDriverList(resolve);  //请求数据
      }).then(function () {
          showDriverList(); //刷新列表数据
          $.Pro('更新成功');
      })
  });

  //Delete Router
   $(document).on('click','.deleteRouter',function (e) {
       let _this = $(this);
       let routerId = $(this).data('router');
       Router.getInstance().removeRouter( routerId );
       Polygon.removePloygonFromMap( routerId );
       deleteRouterFromService(routerId).then(function (valude) {
           $.Pro('移除成功');
           _this.parent().parent().remove();
       },function (error) {
           console.error(error)
       });
       e.stopPropagation();
   });
   /**
    *显示路线 并且隐藏多边形
    *
    */
  $('#show-routes').click(function () {

          Polygon.removeAllPloygon();
          Router.getInstance().showAllRouters();
          Customer.getInstance().hide();
          CONFIG.showRouters = true;
  });

     /**
      *从服务器数据库中删除一条Router信息
      */
    function deleteRouterFromService (routerId) {
        return new Promise(function(resolve,reject){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "{{:url('/router/delete')}}",
                data: {id:routerId},
                success: function (result) {
                    resolve('SUCCESS');
                },
                error:function () {
                    reject('Error')
                }
            });
        })

    }
  //show RouterPoints
   $(document).on('click','.showRoutePoints',function (e) {
       showLoading();
       let routerId = $(this).data('router');
       let driver = $(this).data('driver');
       assignRoute.getInstance().showRoutePoints(routerId,driver);
       colseLoading();
   });
    /**
     *通过司机id查找车辆id
     */
  function getVehicleIdByDriverId( driverId )
  {
      for( let id in OBJECT.driverList)
      {
          if(OBJECT.driverList[id].driver_id == driverId )
          {
              return OBJECT.driverList[id].vehicle_id;
          }
      }
      return null;
  }
 /**
  *取消分配司机
  **/
  function unAssignRouterForDriver(routerId)
  {
          OBJECT.routerPonits[routerId].vehicleId = null;
          OBJECT.routerPonits[routerId].driverId = null;
          Router.getInstance().setRouterUpdateStatus( routerId , false);
          $.Pro('取消成功');

  }

  /*展开和收起左侧工作台*/
  $('.open-show-btn').click(function () {
       if($(this).hasClass('open')){
            $(this).addClass('colse').removeClass('open');
            $('.work-area').animate({width:"0px"},700);
            $('#map').animate({width:"100%"},700);
       }else{
           let wWid = $(window).width();
           let mapWid = wWid - 700;
           $(this).addClass('open').removeClass('colse');
           $('.work-area').animate({width:"700px"},700);
           $('#map').animate({width:`${mapWid}px`},700);
       }
  });

   /**
    * 未排站遗漏的站点
    *  1 统计OBJECT.customerPositionList 长度 as total
    *  2 计算每个多边形的客户数量               as EveryCount
    *  3 UnCheckPoints = total -( sum(EveryCount) )
    */
   function  checkUnAssignPonits() {
       let total = OBJECT.customerPositionList.length;
       let count = 0;
       for( let index in OBJECT.routerPonits )
       {
           if(OBJECT.routerPonits[index].points)
           {
               count = count + OBJECT.routerPonits[index].points.length;
           }
       }
       let UnCheckDropPonitsNum = total - count;
       if( UnCheckDropPonitsNum > 0 )
       {
           let html=` UnAssign Points <span class="warning">${UnCheckDropPonitsNum}</span>`;
           $('.un-assign-warning').html(html);
       }else{
           let html=` UnAssign Points <span>0</span>`;
           $('.un-assign-warning').html(html);

       }
       //setTimeout('checkUnAssignPonits()',1000)
   }

   /**
    * 检查迟到站点
    */
   function  checkDelayPoints() {
       assignRoute.getInstance().countDelayPoints();
       let  delayPointsCounter = CONFIG.delayPointsCounter;
       if( delayPointsCounter  )
       {
           let html=`Delay Points <span class="warning">${delayPointsCounter}</span>`;
           $('.delay-warning').html(html);
       }else{
           let html=` Delay Points <span class="">${delayPointsCounter}</span>`;
           $('.delay-warning').html(html);
       }
       //setTimeout('checkDelayPoints()',1000)
   }

   /**
    *显示画图控件
    */
   function showDrawController()
   {
       drawingManager.setMap(map);
   }

  // setTimeout('checkUnAssignPoints()',CONFIG.checkUnAssignTimeInterval);
/*捕获全局异常*/
   window.addEventListener("error", function (e) {

       colseLoading();
       try{
           $.ajax({
               type: "POST",
               dataType: "json",
               url: '{{:url("/log/debug")}}' ,
               data: {message:e.error.message,filename:e.filename,lineno:e.lineno},
               success: function (result) {}
           });
       }catch (e)
       {

       }

       return false;
   })
  /**
   *迟到的或者超出工作小时Router用红色标出来
   * 选中的item用颜色heightline出来
   */
  function updateExceptionRouter()
  {
      let routers = $('.showRoutePoints');
      $.each(routers,function (index,value) {
          let routerId = $(value).data('router');
          $(value).removeClass('selected-territory');
          if(routerId == CONFIG.currentOpearateRouterId )
          {
              $(value).addClass('selected-territory');
          }
          if(OBJECT.exceptionRouter.has( routerId ))
          {
              $(value).css('color','red');
          }
          if(OBJECT.driverWaitOverOneHour.has(( routerId)))
          {
              $(value).css('color','#1fe4c1');
          }
      })
      setTimeout('updateExceptionRouter()',1000)
  }
  updateExceptionRouter()
  //
  /**
   * 随机返回颜色
   */
  function getRandomColor()
  {
      return CONFIG.routerStrokeColor[Math.floor(Math.random()*CONFIG.routerStrokeColor.length)];
  }

  /**
   * 生成随机RouterId
   */
  function getRandomRouterId()
  {
      return md5(new Date().getTime()+Math.random())
  }


  /**
   *初始化图画信息
   */
   function initApp( routerId ,points,optimizeOrderpoints = true )
   {

      CONFIG.optimizeOrderpoints[routerId] = true;
      OBJECT.routersBgColorMap[routerId] = getRandomColor();
      OBJECT.routersNameMap[routerId] = CONFIG.addRouterNameTempValue;
      OBJECT.routerEdgePoints[routerId] = points;


   }

  /**
   * 队列容器
   * @returns {Promise.<void>}
   * @constructor
   */
   async  function Queue (routerId) {
     try{
         await showLoading();

         if(CONFIG.showRouters == false)
         {
             await  Polygon.draw( routerId );
             await Server.getInstance().assignPointToPolygon(routerId);
         }
         await Router.getInstance().calculateRouterInfo(routerId);
         await assignRoute.getInstance().render();
         await Server.getInstance().updateRouters(routerId);
         await checkUnAssignPonits();
         await checkDelayPoints();
         await colseLoading();
     }catch(error)
     {
         console.error('Error: '+error)
     }

      //await Server.getInstance().assignPointToPolygon();
  }



</script>


<script type="text/javascript">

    layui.use(['form', 'layedit', 'laydate','element'], function(){
        var form = layui.form
            ,layer = layui.layer
            ,layedit = layui.layedit
            ,laydate = layui.laydate
            ,element = layui.element;
        //监听指定开关
        form.on('switch(showDriver)', function(data){
            if(this.checked){
                Driver.getInstance().render();
            }else{
                Driver.getInstance().hide()
            }
        });
        //显示routers
        form.on('switch(showRouter)', function(data){
            let routerId = CONFIG.currentOpearateRouterId;
            if( !routerId )
            {
                $.Pro('请选择一个Territory!');
                return false;
            }
            if(this.checked){
                //移除多边形
                Polygon.removeAllPloygon();
                //显示路线
                Router.getInstance().showAllRouters();
                //隐藏客户标记
                Customer.getInstance().hide();
                CONFIG.showRouters = true;
            }else{
                this.checked = false;
               /* //显示多边形
                Polygon.showAllPloygon()
                //隐藏路线
                Router.getInstance().hideAllRouters();
                //显示客户标记
                Customer.getInstance().show();*/
            }
        });
        /*对客户客户有时间要求的显示Market*/
        form.on('switch(showScheduleTime)', function(data){
            if(this.checked){
                Customer.getInstance().showScheduleTime();
            }else{
                Customer.getInstance().hideScheduleTime();
            }
        });
        element.init();
        form.render();
    });
   // showLoading();
</script>
<!--引入文件区域-->
{include file="router/territory-manage" /}
{include file="router/move" /}
</body>
</html>
